import { createRouter, createWebHashHistory } from "vue-router";
import useStore from "../store";
const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/login',
            name: 'Login',
            component: () => import('@/views/Login/index.vue')
        },
        {
            path: '/',
            component: () => import('@/views/layout/index.vue'),
            redirect: '/home',
            // 下面是二级路由
            children: [
                {
                    path: '/home',
                    component: () => import('@/views/layout/home/index.vue')
                },
                {
                    path: '/question',
                    component: () => import('@/views/layout/question/index.vue')
                },
                {
                    path: '/video',
                    component: () => import('@/views/layout/video/index.vue')
                },
                {
                    path: '/user',
                    component: () => import('@/views/layout/user/index.vue')
                }
            ]
        },
        {
            path: '/search',
            component: () => import('@/views/search/index.vue')
        },
        {
            path: '/article',
            component: () => import('@/views/article/index.vue')
        },
        {
            path: '/searchResult',
            component: () => import('@/views/search/result/index.vue')
        },
        {
            path: '/userProfile',
            component: () => import('@/views/userProfile/index.vue')
        },
        {
            path: '/userChat',
            component: () => import('@/views/userChat/index.vue')
        },
        {
            path: '/404',
            component: () => import('@/views/404.vue')
        }
    ]
})
const AuthUrls = ["/user"];
router.beforeEach((to, from, next) => {
    const { user } = useStore()
    const token = user.tokenInfo.token
    // 如果是去 /login, 判断 token 存不存在, 如果 token 存在说明登录过了, 直接跳转到首页
    if (to.path === '/login' && token) {
        console.log(token, to.path);
        next('/')
        return
    }
    // 如果是需要授权的页面
    if (AuthUrls.includes(to.path)) {
        // 进行验证身份
        console.log(token);
        if (token) {
            next();
        } else {
            // 拦截到登录
            next({
                path: "/login",
                query: {
                    backto: to.fullPath,
                },
            });
        }
    } else {
        next();
    }
});

export default router